<?php

namespace App\Service\OpenShop\Message;

use App\Http\Middleware\OpenShop\UserPermissionAuth;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsShopApi;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\OpenShop\Feishu\MessageSendService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;


/**
 *
 * @property $shopCode 门店编号 e.g. 1122
 * @property $shopName 门店名称 e.g. 上海数字研发
 *
 */
class SendFsService extends BaseMessageService
{
    /**
     * 筹备信息推送
     *
     * @throws GuzzleException
     */
    public function choubeiSend()
    {
        $template     = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderShouyin.json');
        $templateJson = json_decode($template, true);
        $userInfo     = $this->getSignOrder()->orderManagerRel->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_4)
                                                              ->first();
        $fsId         = current(collect(RmsUserRemote::getRmsUserByIds([$userInfo->managerUid ?? '']))
            ->pluck('feishuUserId')
            ->filter()
            ->values()->toArray());

        MessageSendService::sendMessage($fsId, 'user_id', $templateJson, 'interactive',
            UserPermissionAuth::MODULE_OPEN_SHOP);
    }

    /**
     * 提醒筹备信息推送
     *
     * @throws GuzzleException
     */
    public function notifyChoubeiSend()
    {
        $template = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderNotifyShouyin.json');

        $userInfo     = $this->getSignOrder()->orderManagerRel->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_4)
                                                              ->first();
        $templateJson = json_decode(vsprintf($template, [$userInfo->managerName]), true);
        MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_OPEN_SHOP, [
            'e119e19f',
            'gc8644aa'
        ]);
    }


    /**
     * 提醒督导商户通信息推送
     *
     * @throws GuzzleException
     */
    public function notifyChoubeiShangHuTongSend()
    {
        $template = $this->getTemplateFile('WorkOrder/feishu/notifyTemplate/workOrderDianPin.json');

        $userInfo = $this->getSignOrder()->orderManagerRel;

        $dudao   = $userInfo->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_5)->first();
        $choubei = $userInfo->where('type', OpenShopOrderManagerModel::MANAGER_TYPE_4)->first();

        // 获取门店筹备
        $templateJson = json_decode(vsprintf($template, [$choubei->managerName ?? '']), true);

        if (empty($dudao)) {
            $fsId = [];
        } else {
            $fsId = current(collect(RmsUserRemote::getRmsUserByIds([$dudao->managerUid]))
                ->pluck('feishuUserId')
                ->filter()
                ->values()->toArray());
        }

        if (checkEnv('prod')) {
            $fsId = array_merge([$fsId], [
                '2c54915f', // 胡迪
            ]);
        } else {
            $fsId = array_merge([$fsId], [
                '3fgc8798', // xm
                '9acce1b7', // 风雪
                '2c54915f', // 胡迪
            ]);
        }


        $result = MessageSendService::batchSendCardMessage($templateJson, UserPermissionAuth::MODULE_OPEN_SHOP, $fsId);

        Log::info('shanghutong_notify_3', [
            'templateJson' => $templateJson,
            'orderNo'      => $this->orderNo,
            'fsId'         => $fsId,
            'sendResult'   => $result
        ]);

        // 美团点评商户通支付完成通知机器人-推送群(上面单个人会一直换，之后统一推送群)
        BuildFs::newRobot(SendFs::ROBOT_MERCHANT_PAY_SUCCESS, BuildFs::MSG_TYPE_CARD)
            ->setCardContent($templateJson)
            ->send();
    }


    private function getUrl()
    {
        $path  = "workOrder/manage/info/{$this->workOrderApplyMainModel->workOrderNo}?isMainModule=1";
        $appid = config("feishu." . UserPermissionAuth::MODULE_WORK_ORDER . ".appID");

        return "https://applink.feishu.cn/client/web_app/open?appId={$appid}&path=$path";
    }


    public function getTemplateFile(string $filePath)
    {
        $template = file_get_contents(resource_path($filePath));
        $result   = array();
        preg_match_all("/\{\{(.*)\}\}/U", $template, $result);


        $params        = [];
        $paramsBracket = [];
        foreach ($result[1] as $value) {
            $params[$value]                      = $this->$value;
            $paramsBracket['{{' . $value . '}}'] = $this->$value;
        }
        $paramsKeys   = array_keys($paramsBracket);
        $paramsValues = array_values($paramsBracket);

        $template = str_replace($paramsKeys, $paramsValues, $template);

        return $template;
    }

    public function __get($paramName)
    {
        if (method_exists($this, 'get' . $paramName)) {
            return call_user_func([$this, 'get' . $paramName]);
        } else {
            dd('方法:' . 'get' . $paramName . '不存在');
        }
    }

}
